package com.example.servlet;

import com.example.dao.decreaseDao;
import com.example.dao.decreaseDaoImpl;
import com.example.entity.decrease;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import com.google.gson.Gson;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/getDecreaseData")
public class decreaseServlet extends HttpServlet {

    private decreaseDao decreaseDao;

    @Override
    public void init() throws ServletException {
        try {
            decreaseDao = new decreaseDaoImpl();
        } catch (SQLException e) {
            throw new ServletException("DAO 初始化失败", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        String timeRange = request.getParameter("timeRange");
        String sortBy = request.getParameter("sortBy");

        System.out.println("Received request - timeRange: " + timeRange + ", sortBy: " + sortBy);

        List<decrease> data = null;

        try {
            switch (timeRange) {
                case "today":
                    data = "amount".equals(sortBy) ?
                            decreaseDao.getTodayDecreaseByAmount() :
                            decreaseDao.getTodayDecreaseByPercentage();
                    break;
                case "yesterday":
                    data = "amount".equals(sortBy) ?
                            decreaseDao.getYesterdayDecreaseByAmount() :
                            decreaseDao.getYesterdayDecreaseByPercentage();
                    break;
                case "this_week":
                    data = "amount".equals(sortBy) ?
                            decreaseDao.getThisWeekDecreaseByAmount() :
                            decreaseDao.getThisWeekDecreaseByPercentage();
                    break;
                case "this_month":
                    data = "amount".equals(sortBy) ?
                            decreaseDao.getThisMonthDecreaseByAmount() :
                            decreaseDao.getThisMonthDecreaseByPercentage();
                    break;
                default:
                    data = decreaseDao.getTodayDecreaseByAmount();
            }

            if (data == null || data.isEmpty()) {
                System.out.println("No data found for the query");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No data found");
                return;
            }

            response.setContentType("application/json;charset=UTF-8");
            String json = new Gson().toJson(data);
            System.out.println("Sending JSON: " + json);
            response.getWriter().write(json);

        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误: " + e.getMessage());
        }
    }
}
